/*
 * @LastEditTime: 2024-09-10 00:33:55
 */
import axios from 'axios';
import router from '@/router'

let baseUrl = process.env.VUE_APP_BASE_API;
const CancelToken = axios.CancelToken;

const instance = axios.create({
	timeout: 500000, // 可选的：设置请求超时（毫秒）
});

let configs_ENC = {
	headers: {
		'enc': false
	}
}

// 添加请求拦截器
instance.interceptors.request.use(function(config) {
	return config;
}, function(error) {
	// 对请求错误做些什么
	console.log(error)
	return Promise.reject(error);
});
/**
 * @响应拦截
 */
instance.interceptors.response.use(response => {
	const endTime = new Date(); // 记录请求结束时间
	const duration = endTime; // 计算接口访问时间
	console.log(`${response.config.url} 请求耗时: ${duration} ms`);

	if (response.status !== 200) {
		return Promise.reject(response)
	}
	/**
	 * @code 登录过期 token验证失败 根据后端调 
	 */
	if (response.data.code == 401) {
		// router.push("/login")
	}
	return response.data
}, error => {
	const endTime = new Date();
	const duration = endTime;
	console.error(error);
	let err = {
		success: false,
		msg: "未知异常，请联系管理员！"
	}
	return Promise.reject(err)
})

//处理是否加密数据
let isEncryptionParam = (params) => {
	return params
}
export const GET = async (url, params) => {
	try {
		params = isEncryptionParam(params)
		const data = await instance.get(`${baseUrl}${url}`, {
			params: params,
			headers: configs_ENC.headers
		}, configs_ENC);
		return data;
	} catch (error) {
		return error;
	}
}
//没有基地址 访问根目录下文件

export const GETNOBASE = async (url, params) => {
	try {
		const data = await instance.get(url, {
			params: params,
		});
		return data;
	} catch (error) {
		return error;
	}
}
export const POST = async (url, params) => {
	try {
		params = isEncryptionParam(params)
		const data = await instance.post(`${baseUrl}${url}`, params, configs_ENC);
		return data;
	} catch (error) {
		return error;
	}
}

// call localhost jar
export const LocalPOST = async (url, params) => {
	try {
		params = isEncryptionParam(params)
		const data = await instance.post(`${url}`, params, configs_ENC);
		return data;
	} catch (error) {
		return error;
	}
}

export const PUT = async (url, params) => {
	try {
		params = isEncryptionParam(params)
		const data = await instance.put(`${baseUrl}${url}`, params, configs_ENC);
		return data;
	} catch (error) {
		return error;
	}
}